<!--
 * @Description: 本地导入弹框 
 * @Author: 黄勇
 * @Date: 2020-03-09 15:36:26
 * @LastEditTime: 2020-03-24 21:25:27
 * @LastEditors: 黄勇
 -->
<template>
    <el-dialog title="从本地导入" :visible.sync="isShow" width="500px">
        
        <div>
            <el-input
                class="file-input"
                v-model="input" 
                size="small"
                disabled>
            </el-input>
            <el-upload
                ref="upload"
                class="upload-file"
                :action="actionUrl"
                :data="upLoadData"
                name="importfile"
                :http-request="uploadFile"
                
                :on-success="onSuccess"
                :on-error="onError"
                :on-change="onChange"
                :on-progress="onProgress"
                
                :on-exceed="handleExceed"
                :show-file-list="false"
                :auto-upload="false"
                :file-list="fileList">
                <el-button size="small"  round  type="primary">点击上传</el-button>
            </el-upload>
        </div>

        <!-- 检查应用是否存在提示框 -->
        <el-dialog title="系统提示" :visible.sync="appCacheDialogShow" append-to-body>

            <app-icon slot="reference" iconName="vcloud-wodedingdan" className="org-info__icon cursor-pointer"></app-icon>
            <span>当前应用已存在，请选择更新或生成新应用</span>
            <br>

            <!-- 继续更新提示框 -->
            <el-dialog title="更新提示" :visible.sync="updateDialogShow" append-to-body>
                <app-icon slot="reference" iconName="vcloud-wodedingdan" className="org-info__icon cursor-pointer"></app-icon>
                <span>
                    系统将对应用"合同管理"进行更新，请务必做好该应用及数据库备份！
                    应用更新后，无法还原到更新前版本！
                </span>
                <br>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitUpdateBtn">继续更新</el-button>
                    <el-button @click="updateDialogShow=false">取 消</el-button>
                </span>
            </el-dialog>

            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="updateBtn">更 新</el-button>
                <el-button @click="createAppBtn">生成新应用</el-button>
                <el-button @click="appCacheDialogShow=false">取 消</el-button>
            </span>
        </el-dialog>

        <span slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button type="primary" @click="submitBtn">确 定</el-button>
        </span>

    </el-dialog>
    
    

</template>

<script>

// import loading from "@/utils/util.js"
import Axios from 'axios'

export default {
    name: "upload",
    props: {
        
    },
    components: {
        // loading
    },
    computed: {},
    data: () => ({

        // 组件接口参数
        isShow:false,
        fileType:[],
        userInfo:{},
        localRefresh:false,

        updateDialogShow:false,//继续更新提示弹框
        appCacheDialogShow:false,//应用已存在提示弹框
        upLoadData:{},
        input: '',
        fileList:[], //文件列表，目前只支持一个文件上传
        fileData:{},
        actionUrl:"#",
        targetCorpid:"",
        
    }),
    created() {
        
    },
    mounted() {

    },
    watch: {
        //input的值删除后，文件列表也需要删除
        input(){
            if(this.input == ""){
                this.fileList=[];
                this.$refs.upload.clearFiles();//清除记录
            }
        }
    },
    methods: {
        // 组件入口
        open(data){
            if(data){
                this.input = ""
                if(this.$refs.upload) this.$refs.upload.clearFiles()
                // this.isShow = data.isShow;
                this.fileType = data.fileType;
                this.userInfo = data.userInfo;
                this.localRefresh = data.localRefresh;
                this.$nextTick(()=>{
                    this.isShow = true;
                    // this.getDesignCenterId();
                })
            }
        },
        //获取云设计中心id
        // getDesignCenterId(){
        //     this.api.getDesignCenterId(
        //         {},
        //         {method:"get",customRequest:true }
        //     ).then(res => {
        //         console.log(res);
        //         this.targetCorpid = res.data.corpid;
        //     }).catch(err => {
        //         console.log(err);
        //     });
        // },
        //文件状态发生改变时监听
        onChange(file){
            console.log("change:" + JSON.stringify(file))
            if(file.status == 'ready'){
                // const fileType = file.name.split('.')[1] === 'wps';//格式
                const fileMaxSize10M = file.size / 1024 / 1024 < 10; //10M? 
                console.log("文件小于10M? "+fileMaxSize10M)
                //文件大小判断
                if (!fileMaxSize10M) {
                    this.$alert('上传文件大小不能超过 10MB!');
                    return fileMaxSize10M;
                }
                //判断传入的文件类型，与当前选择的文件的类型是否匹配
                let fileName = file.name.lastIndexOf(".");
                let fileNameLength = file.name.length;//取到文件名长度
                let fileFormat = file.name.substring(fileName + 1, fileNameLength);//截
                if(this.fileType.indexOf(fileFormat) > -1 ){
                    this.fileList = [];
                    this.input = file.name;
                    this.fileList.push(file);
                }else{
                    this.$alert('不支持此文件!');
                    return false;
                }
                this.$refs.upload.clearFiles();//清除记录
            }
        },

        //文件上传成功时的钩子
        onSuccess(response,file, fileList){
            console.log("onSuccess")
            this.$message({
                message: '文件上传成功',
                type: 'success'
            })
            this.$refs.upload.clearFiles();//清除记录
            // let data = {
            //     file:file
            // }
            // this.$emit("uploadSuccess", data)
        },

        //文件上传失败时的钩子
        onError(err, file, fileList){
            console.log("onError")
            console.log(err);
            this.$message.error(err.msg);
        },

        //文件上传时
        onProgress(event, file, fileList){
            console.log(event);
            // this.$loading.show("上传中...");
            if(event.percent == 100 ){ //上传进度到100的时候
                // this.$loading.hide();
                console.log("文件上传完成");
                // this.isShow = false;
            }
        },

        //文件选择个数监听
        handleExceed(files, fileList) {
            this.$message.warning('当前只允许选择1个文件!');
        },
        closeDialog(){
            this.fileList = [];
            this.input = "";
            this.$refs.upload.clearFiles();//清除记录
            this.isShow = false;
        },
        // 点击确定按钮
        submitBtn(file){
            // this.isShow = false;
            if(this.fileList.length == 0 ){
               this.$message.warning('请选择至少1个文件!'); 
               return;
            }
            this.$refs.upload.submit();
        },
        //确定按钮后的文件上传
        uploadFile(params){
            console.log("uploadFile", params);
            let config = {
                headers: { "Content-Type": "multipart/form-data" }
            }
            //从云设计中心 上传到目标客户
            const param = new FormData();
            param.append("file", params.file);
            param.append('spaceId',this.userInfo.spaceId);
            // param.append('corpid',"185307117148700672"); //目标云联ID (70环境) 
            // param.append('corpid',this.userInfo.userCorpId); //用户云联id  corpid
            // param.append('targetCorpid',this.targetCorpid);  //(云设计中心云联ID) targetCorpid  
            
            const loading = this.$loading({
                // lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            Axios.post(
                "/designCenter/pkg/upload",param,config,{ timeout: 60000 } //最大上传时间
            ).then(res => {
                loading.close();
                console.log(res);
                let uploadData = res.data;
                if(uploadData.data){
                    this.fileData.fileId = uploadData.data.fileId;
                    //执行安装之前，需要检查下应用是否已存在
                    this.checkApp(uploadData);
                }else{
                    this.$alert('接口返回参数异常:'+JSON.stringify(res.data));
                }
            }).catch(err => {
                loading.close();
                // console.warn(err.message);
                this.$alert(err.msg || err.message);
            });
        },
        //检查应用是否已存在
        checkApp(uploadData){
            this.api.checkAppInstall({
                fileId:uploadData.data.fileId
            }).then(res => {
                console.log(res);
                let data = res.data;
                if(this.localRefresh){ //是否是本地更新入口
                    this.submitUpdateBtn();//直接更新
                }else{
                    if(data.exist){ //如果重复
                        this.appCacheDialogShow = true; //打开更新提示,走本地更新
                    }else { //如果不重复-直接走创建新应用
                        const type = 1;
                        this.openAppInstall(type);
                    }
                }
            }).catch(err => {
                console.warn(err.msg);
                this.$alert(err.msg || err.message);
            });
        },
        //点击更新按钮
        updateBtn(){
           this.closeDialog();
           this.updateDialogShow = true;
           this.appCacheDialogShow = false;
        },
        //点击继续更新按钮
        submitUpdateBtn(){
            this.closeDialog();
            this.updateDialogShow = false;
            const type = 2; 
            this.openAppInstall(type);
        },
        //点击生成新应用按钮
        createAppBtn(){
            this.closeDialog();
            this.appCacheDialogShow = false;
            const type = 1;
            this.openAppInstall(type);
        },
        //触发最终回调
        openAppInstall(type){
            //type 1  创建新应用   2 本地更新应用   3 更新在线应用
            const fileId = this.fileData.fileId;
            const params = {
                fileId:fileId,
                type:type
            }
            var data = {
                "url":"",
                "title":"应用安装向导",
                "source":"",
                "fileId":fileId,
                "setupType":"local",
                "resetId":false,
                "upgrade":type==1?false:true, //true:更新 false:生成新应用
                "upgradeAppId":"",
                "version":""
            }
            params.data = data;
            this.closeDialog();
            this.$emit("openAppInstall", params);
            // this.$emit('close');
        }


    
    }
};
</script>


<style lang="scss" scoped>
.file-input{
    width: 310px;
    margin-right: 20px;
}
.upload-file{
    display: inline-block;
    button{
        width: 120px;
    }
}

</style>